// 历史记录页面 - iOS风格
Page({
  data: {
    historyList: [],
    selectMode: false,
    selectedItems: [],
    showDetail: false,
    currentItem: null,
    searchValue: '',
    showSearch: false,
    currentPage: 1,
    pageSize: 20,
    hasMore: true,
    loading: false
  },

  onLoad(options) {
    this.loadHistory();
    
    // 如果没有历史记录，创建一些测试数据
    if (options.demo === 'true') {
      this.createTestData();
    }
  },

  onShow() {
    // 每次显示页面时重新加载历史记录
    this.loadHistory();
  },

  // 加载历史记录
  loadHistory() {
    try {
      const historyManager = require('../../utils/history-manager.js');
      const scanHistory = historyManager.getHistory('scanHistory');
      
      // 只显示扫描历史记录，不包含生成记录
      const allHistory = scanHistory.map(item => ({ ...item, source: 'scan' }));
      
      // 按时间排序（最新的在前面）
      allHistory.sort((a, b) => {
        const timeA = a.scanTime || a.timestamp || 0;
        const timeB = b.scanTime || b.timestamp || 0;
        return timeB - timeA;
      });
      
      const processedHistory = allHistory.map(item => this.processHistoryItem(item));
      
      this.setData({
        historyList: processedHistory,
        selectMode: false,
        selectedItems: [],
        hasMore: false // 暂时不支持分页
      });
    } catch (error) {
      console.error('加载历史记录失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },

  // 处理历史记录项
  processHistoryItem(item) {
    const now = new Date();
    const recordTime = new Date(item.scanTime || item.timestamp || item.time);
    const timeDiff = now - recordTime;
    
    // 格式化时间显示
    let timeText = '';
    let fullTime = this.formatFullTime(recordTime);
    
    if (timeDiff < 60000) { // 1分钟内
      timeText = '刚刚';
    } else if (timeDiff < 3600000) { // 1小时内
      timeText = Math.floor(timeDiff / 60000) + '分钟前';
    } else if (timeDiff < 86400000) { // 24小时内
      timeText = Math.floor(timeDiff / 3600000) + '小时前';
    } else if (timeDiff < 604800000) { // 7天内
      timeText = Math.floor(timeDiff / 86400000) + '天前';
    } else {
      timeText = this.formatDate(recordTime);
    }

    // 识别内容类型
    const contentType = this.identifyContentType(item.content);
    
    // 生成预览文本
    const preview = this.generatePreview(item.content, contentType);
    
    // 生成额外信息
    const extra = this.generateExtraInfo(item.content, contentType);

    return {
      ...item,
      timeText,
      fullTime,
      type: contentType.type,
      typeText: contentType.text,
      sourceText: item.source === 'generate' ? '生成' : '扫描',
      preview,
      extra,
      selected: false
    };
  },

  // 识别内容类型
  identifyContentType(content) {
    // URL检测
    if (/^https?:\/\/.+/i.test(content)) {
      return { type: 'url', text: '网址' };
    }
    
    // WiFi信息检测
    if (/^WIFI:/i.test(content)) {
      return { type: 'wifi', text: 'WiFi' };
    }
    
    // 电话号码检测
    if (/^tel:/i.test(content) || /^(\+?86)?1[3-9]\d{9}$/.test(content)) {
      return { type: 'phone', text: '电话' };
    }
    
    // 联系人信息检测
    if (/^BEGIN:VCARD/i.test(content)) {
      return { type: 'contact', text: '联系人' };
    }
    
    // 邮箱检测
    if (/^mailto:/i.test(content) || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(content)) {
      return { type: 'email', text: '邮箱' };
    }
    
    // 地理位置检测
    if (/^geo:/i.test(content)) {
      return { type: 'location', text: '位置' };
    }
    
    // 默认为文本
    return { type: 'text', text: '文本' };
  },

  // 生成预览文本
  generatePreview(content, contentType) {
    const maxLength = 100;
    
    switch (contentType.type) {
      case 'wifi':
        const wifiMatch = content.match(/S:([^;]*)/);
        return wifiMatch ? `WiFi: ${wifiMatch[1]}` : content.substring(0, maxLength);
      
      case 'url':
        try {
          const url = new URL(content);
          return url.hostname + url.pathname;
        } catch {
          return content.substring(0, maxLength);
        }
      
      case 'phone':
        return content.replace(/^tel:/, '');
      
      case 'email':
        return content.replace(/^mailto:/, '');
      
      default:
        return content.length > maxLength ? 
          content.substring(0, maxLength) + '...' : content;
    }
  },

  // 生成额外信息
  generateExtraInfo(content, contentType) {
    switch (contentType.type) {
      case 'wifi':
        const passwordMatch = content.match(/P:([^;]*)/);
        return passwordMatch && passwordMatch[1] ? '需要密码' : '开放网络';
      
      case 'url':
        try {
          const url = new URL(content);
          return url.protocol === 'https:' ? '安全连接' : '普通连接';
        } catch {
          return null;
        }
      
      case 'contact':
        const nameMatch = content.match(/FN:([^\r\n]*)/);
        return nameMatch ? `联系人: ${nameMatch[1]}` : null;
      
      default:
        return null;
    }
  },

  // 格式化完整时间
  formatFullTime(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    const second = String(date.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
  },

  // 格式化日期
  formatDate(date) {
    const month = date.getMonth() + 1;
    const day = date.getDate();
    return `${month}月${day}日`;
  },

  // 切换选择模式
  toggleSelectMode() {
    this.setData({
      selectMode: !this.data.selectMode,
      selectedItems: []
    });
  },

  // 切换选择项
  toggleSelect(e) {
    const { item } = e.currentTarget.dataset;
    const selectedItems = [...this.data.selectedItems];
    const index = selectedItems.indexOf(item.id);
    
    if (index >= 0) {
      selectedItems.splice(index, 1);
    } else {
      selectedItems.push(item.id);
    }
    
    this.setData({ selectedItems });
  },

  // 查看详情
  viewDetail(e) {
    const { item } = e.currentTarget.dataset;
    this.setData({
      currentItem: item,
      showDetail: true
    });
  },

  // 隐藏详情
  hideDetail() {
    this.setData({
      showDetail: false,
      currentItem: null
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 空函数，用于阻止事件冒泡
  },

  // 复制内容
  copyContent(e) {
    // 阻止事件冒泡
    e.stopPropagation && e.stopPropagation();
    
    const content = e.currentTarget.dataset.content;
    
    wx.setClipboardData({
      data: content,
      success: () => {
        wx.showToast({
          title: '已复制',
          icon: 'success'
        });
        
        // 如果是在弹窗中，关闭弹窗
        if (this.data.showDetail) {
          this.hideDetail();
        }
      },
      fail: () => {
        wx.showToast({
          title: '复制失败',
          icon: 'none'
        });
      }
    });
  },

  // 分享内容
  shareContent(e) {
    // 阻止事件冒泡
    e.stopPropagation && e.stopPropagation();
    
    const item = e.currentTarget.dataset.item;
    
    wx.showActionSheet({
      itemList: ['发送给朋友', '分享到朋友圈', '复制链接'],
      success: (res) => {
        switch (res.tapIndex) {
          case 0:
            // 发送给朋友的逻辑
            wx.showToast({
              title: '功能开发中',
              icon: 'none'
            });
            break;
          case 1:
            // 分享到朋友圈的逻辑
            wx.showToast({
              title: '功能开发中',
              icon: 'none'
            });
            break;
          case 2:
            // 复制链接
            this.copyContent({ currentTarget: { dataset: { content: item.content } } });
            break;
        }
        
        // 如果是在弹窗中，关闭弹窗
        if (this.data.showDetail) {
          this.hideDetail();
        }
      }
    });
  },

  // 删除选中项
  deleteSelected() {
    if (this.data.selectedItems.length === 0) return;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除选中的 ${this.data.selectedItems.length} 条记录吗？`,
      confirmText: '删除',
      confirmColor: '#dc2626',
      success: (res) => {
        if (res.confirm) {
          this.performDelete(this.data.selectedItems);
        }
      }
    });
  },

  // 清空所有历史
  clearAllHistory() {
    wx.showModal({
      title: '确认清空',
      content: '确定要清空所有历史记录吗？此操作不可恢复。',
      confirmText: '清空',
      confirmColor: '#dc2626',
      success: (res) => {
        if (res.confirm) {
          this.performClearAll();
        }
      }
    });
  },

  // 执行删除
  performDelete(idsToDelete) {
    try {
      const historyManager = require('../../utils/history-manager.js');
      const success = historyManager.deleteHistoryItems('scanHistory', idsToDelete);
      
      if (success) {
        wx.showToast({
          title: '删除成功',
          icon: 'success'
        });
        // 重新加载数据
        this.loadHistory();
      } else {
        wx.showToast({
          title: '删除失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('删除失败:', error);
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  },

  // 执行清空
  performClearAll() {
    try {
      const historyManager = require('../../utils/history-manager.js');
      const success = historyManager.clearHistory('scanHistory');
      
      if (success) {
        wx.showToast({
          title: '清空成功',
          icon: 'success'
        });
        // 重新加载数据
        this.loadHistory();
      } else {
        wx.showToast({
          title: '清空失败',
          icon: 'none'
        });
      }
    } catch (error) {
      console.error('清空失败:', error);
      wx.showToast({
        title: '清空失败',
        icon: 'none'
      });
    }
  },

  // 跳转到扫码页面
  goToScan() {
    // 直接跳转到首页并触发扫码
    wx.reLaunch({
      url: '/pages/index/index?autoScan=true'
    });
  },

  // 创建测试数据
  createTestData() {
    const testData = [
      {
        id: '1',
        content: 'https://www.baidu.com',
        scanTime: Date.now() - 60000 // 1分钟前
      },
      {
        id: '2',
        content: 'WIFI:T:WPA;S:MyWiFi;P:password123;H:false;;',
        scanTime: Date.now() - 3600000 // 1小时前
      },
      {
        id: '3',
        content: '13812345678',
        scanTime: Date.now() - 86400000 // 1天前
      },
      {
        id: '4',
        content: 'BEGIN:VCARD\nVERSION:3.0\nFN:张三\nTEL:13800138000\nEND:VCARD',
        scanTime: Date.now() - 172800000 // 2天前
      },
      {
        id: '5',
        content: '这是一段普通的文本内容，用于测试文本类型的二维码识别功能。',
        scanTime: Date.now() - 259200000 // 3天前
      }
    ];
    
    try {
      wx.setStorageSync('scanHistory', testData);
      this.loadHistory();
      wx.showToast({
        title: '测试数据已创建',
        icon: 'success'
      });
    } catch (error) {
      console.error('创建测试数据失败:', error);
    }
  },

  // 搜索功能
  onSearchInput: function(e) {
    var value = e.detail.value;
    this.setData({
      searchValue: value
    });
    
    // 实时搜索
    this.performSearch(value);
  },

  // 执行搜索
  performSearch: function(keyword) {
    if (!keyword.trim()) {
      this.loadHistory();
      return;
    }
    
    try {
      var scanHistory = wx.getStorageSync('scanHistory') || [];
      
      // 过滤匹配的记录
      var filteredHistory = scanHistory.filter(function(item) {
        var content = item.content || '';
        return content.toLowerCase().includes(keyword.toLowerCase());
      });
      
      // 合并并处理
      var allHistory = filteredHistory.map(function(item) {
        return Object.assign({}, item, { source: 'scan' });
      });
      
      // 按时间排序
      allHistory.sort(function(a, b) {
        return (b.scanTime || b.timestamp || 0) - (a.scanTime || a.timestamp || 0);
      });
      
      // 处理每个项目
      var processedHistory = allHistory.map(this.processHistoryItem.bind(this));
      
      this.setData({
        historyList: processedHistory
      });
      
    } catch (error) {
      console.error('搜索失败:', error);
    }
  },

  // 清空搜索
  clearSearch: function() {
    this.setData({
      searchValue: '',
      showSearch: false
    });
    this.loadHistory();
  },

  // 显示搜索框
  showSearchInput: function() {
    this.setData({
      showSearch: true
    });
  },

  // 隐藏搜索框
  hideSearchInput: function() {
    this.setData({
      showSearch: false,
      searchValue: ''
    });
    this.loadHistory();
  },

  // 点击历史记录项目
  onItemTap: function(e) {
    var item = e.currentTarget.dataset.item;
    
    if (this.data.selectMode) {
      // 选择模式下切换选中状态
      this.toggleItemSelection(item);
    } else {
      // 正常模式下处理内容
      this.processItemContent(item.content);
    }
  },

  // 处理项目内容
  processItemContent: function(content) {
    // URL处理
    if (/^https?:\/\/.+/i.test(content)) {
      wx.showModal({
        title: '发现网址',
        content: content,
        confirmText: '复制',
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            // 复制到剪贴板
            wx.setClipboardData({
              data: content,
              success: function() {
                wx.showToast({
                  title: '已复制',
                  icon: 'success'
                });
              }
            });
          }
        }
      });
      return;
    }
    
    // WiFi信息处理
    if (/^WIFI:/i.test(content)) {
      var wifiMatch = content.match(/WIFI:T:([^;]*);S:([^;]*);P:([^;]*);H:([^;]*);?/);
      if (wifiMatch) {
        var wifiInfo = '网络名称: ' + wifiMatch[2] + '\n' +
                        '密码: ' + wifiMatch[3] + '\n' +
                        '加密类型: ' + wifiMatch[1];
        
        wx.showModal({
          title: 'WiFi信息',
          content: wifiInfo,
          confirmText: '复制密码',
          cancelText: '知道了',
          success: function(res) {
            if (res.confirm) {
              wx.setClipboardData({
                data: wifiMatch[3],
                success: function() {
                  wx.showToast({
                    title: '密码已复制',
                    icon: 'success'
                  });
                }
              });
            }
          }
        });
        return;
      }
    }
    
    // 电话号码处理
    if (/^tel:/i.test(content) || /^(\+?86)?1[3-9]\d{9}$/.test(content)) {
      var phoneNumber = content.replace(/^tel:/, '');
      wx.showModal({
        title: '电话号码',
        content: phoneNumber,
        confirmText: '拨打',
        cancelText: '复制',
        success: function(res) {
          if (res.confirm) {
            wx.makePhoneCall({
              phoneNumber: phoneNumber,
              fail: function() {
                wx.showToast({
                  title: '拨打失败',
                  icon: 'none'
                });
              }
            });
          } else if (res.cancel) {
            wx.setClipboardData({
              data: phoneNumber,
              success: function() {
                wx.showToast({
                  title: '已复制',
                  icon: 'success'
                });
              }
            });
          }
        }
      });
      return;
    }
    
    // 邮箱处理
    if (/^mailto:/i.test(content) || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(content)) {
      var email = content.replace(/^mailto:/, '');
      wx.showModal({
        title: '邮箱地址',
        content: email,
        confirmText: '复制',
        showCancel: false,
        success: function(res) {
          if (res.confirm) {
            wx.setClipboardData({
              data: email,
              success: function() {
                wx.showToast({
                  title: '已复制',
                  icon: 'success'
                });
              }
            });
          }
        }
      });
      return;
    }
    
    // 普通文本
    wx.showModal({
      title: '内容详情',
      content: content,
      confirmText: '复制',
      success: function(res) {
        if (res.confirm) {
          wx.setClipboardData({
            data: content,
            success: function() {
              wx.showToast({
                title: '已复制',
                icon: 'success'
              });
            }
          });
        }
      }
    });
  },

  // 进入选择模式
  enterSelectMode: function() {
    this.setData({
      selectMode: true,
      selectedItems: []
    });
  },

  // 退出选择模式
  exitSelectMode: function() {
    this.setData({
      selectMode: false,
      selectedItems: []
    });
    
    // 重置所有项目的选中状态
    var historyList = this.data.historyList.map(function(item) {
      return Object.assign({}, item, { selected: false });
    });
    
    this.setData({
      historyList: historyList
    });
  },

  // 切换项目选中状态
  toggleItemSelection: function(targetItem) {
    var historyList = this.data.historyList;
    var selectedItems = this.data.selectedItems.slice(); // 复制数组
    
    // 找到目标项目并切换选中状态
    for (var i = 0; i < historyList.length; i++) {
      if (historyList[i].id === targetItem.id) {
        historyList[i].selected = !historyList[i].selected;
        
        if (historyList[i].selected) {
          // 添加到选中列表
          selectedItems.push(historyList[i]);
        } else {
          // 从选中列表移除
          selectedItems = selectedItems.filter(function(item) {
            return item.id !== targetItem.id;
          });
        }
        break;
      }
    }
    
    this.setData({
      historyList: historyList,
      selectedItems: selectedItems
    });
  },

  // 全选
  selectAll: function() {
    var historyList = this.data.historyList.map(function(item) {
      return Object.assign({}, item, { selected: true });
    });
    
    this.setData({
      historyList: historyList,
      selectedItems: historyList.slice()
    });
  },

  // 取消全选
  deselectAll: function() {
    var historyList = this.data.historyList.map(function(item) {
      return Object.assign({}, item, { selected: false });
    });
    
    this.setData({
      historyList: historyList,
      selectedItems: []
    });
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '小籽二维码 - 扫码生成一站式服务',
      path: '/pages/index/index'
    };
  }
});

// 工具函数：保存扫描记录
export function saveScanRecord(content) {
  const historyManager = require('../../utils/history-manager.js');
  return historyManager.saveScanRecord(content);
} 